package auth

import (
	"crypto/rand"
	"encoding/hex"
	"fmt"
	"time"

	"github.com/google/uuid"
)

// ChallengeInfo 存储挑战信息
type ChallengeInfo struct {
	ID         string    `json:"challenge_id"`
	Nonce      string    `json:"nonce"`
	DeviceID   string    `json:"-"`
	ExpiresAt  time.Time `json:"expires_at"`
}

// ChallengeStore 存储挑战信息
type ChallengeStore struct {
	challenges map[string]ChallengeInfo
}

// NewChallengeStore 创建新的挑战存储
func NewChallengeStore() *ChallengeStore {
	return &ChallengeStore{
		challenges: make(map[string]ChallengeInfo),
	}
}

// GenerateChallenge 生成新的挑战
func (cs *ChallengeStore) GenerateChallenge(deviceID string, duration time.Duration) (*ChallengeInfo, error) {
	// 生成随机 nonce (64位十六进制字符串)
	nonceBytes := make([]byte, 32)
	if _, err := rand.Read(nonceBytes); err != nil {
		return nil, fmt.Errorf("生成随机数失败: %v", err)
	}
	nonce := hex.EncodeToString(nonceBytes)
	
	// 生成唯一ID
	id := uuid.New().String()
	
	// 创建挑战信息
	challenge := ChallengeInfo{
		ID:        id,
		Nonce:     nonce,
		DeviceID:  deviceID,
		ExpiresAt: time.Now().Add(duration),
	}
	
	// 存储挑战
	cs.challenges[id] = challenge
	
	return &challenge, nil
}

// GetChallenge 获取挑战信息
func (cs *ChallengeStore) GetChallenge(id string) (*ChallengeInfo, bool) {
	challenge, exists := cs.challenges[id]
	if !exists {
		return nil, false
	}
	
	// 检查是否过期
	if time.Now().After(challenge.ExpiresAt) {
		delete(cs.challenges, id)
		return nil, false
	}
	
	return &challenge, true
}

// RemoveChallenge 移除挑战
func (cs *ChallengeStore) RemoveChallenge(id string) {
	delete(cs.challenges, id)
}
